package it.blueocean.acanto.web.platform.components.dragdrop;

import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.panel.Panel;
import org.wicketstuff.yui.behavior.dragdrop.YuiDDTarget;
import org.wicketstuff.yui.markup.html.list.YuiDDListView;

public class ListViewPanel<T> extends Panel
{
	private static final long serialVersionUID = -4509914168845424950L;

	private WebMarkupContainer container;

	private WebMarkupContainer listContainer;

	private YuiDDListView<T> listview;
	
	private String groupId = "grp_";
	
	private String targetId;

	/**
	 * 
	 * @param id
	 */
	public ListViewPanel(String id, final List<T> list)
	{
		super(id);
		setOutputMarkupId(true);

		// dd target
		add(container = new WebMarkupContainer("ddTarget"));
		container.setOutputMarkupId(true);
		container.add(new YuiDDTarget(getGroupId())
		{
			private static final long serialVersionUID = 1L;

			@SuppressWarnings("unchecked")
			@Override
			public void onDrop(AjaxRequestTarget target, Component component)
			{
				if(component instanceof ListItem)
				{
					ListItem<?> listItem = (ListItem<?>) component;
					list.add((T) listItem.getModelObject());
				}
				target.addComponent(container);
				onAjaxUpdate(target);
			}
		});

		// list container
		container.add(listContainer = new WebMarkupContainer("list"));
		listContainer.setOutputMarkupId(true);

		listContainer.add(listview = new YuiDDListView<T>("items", list)
		{
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(ListItem<T> item)
			{
				super.populateItem(item);
				item.add(newListItem("item", item));
			}

			@Override
			protected void onAjaxUpdate(AjaxRequestTarget target)
			{
				target.addComponent(listContainer);
				ListViewPanel.this.onAjaxUpdate(target);
			}

			@Override
			protected String getGroupId()
			{
				return ListViewPanel.this.getGroupId();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public List<T> getList()
	{
		return (List<T>) listview.getList();
	}

	public ListViewPanel(String id, List<T> list, String classId, String targetId)
	{
		this(id, list);
		this.groupId = classId;
		this.targetId = targetId;
	}

	protected Component newListItem(String id, ListItem<T> item)
	{
		return new Label(id, (String) item.getModelObject());
	}

	protected String getGroupId()
	{
		if(groupId.equalsIgnoreCase("grp_"))
		{
			return "grp_" + getMarkupId();
		}
		
		return groupId;
	}

	protected void onAjaxUpdate(AjaxRequestTarget target)
	{
		if(this.targetId != null)
		{
			info(this.targetId + " : " + getList());
		}
	}

}
